package com.nantian.security.controller;

import com.cuit.springboot.gdao.user.RoleAbilityMapper;
import com.nantian.logic.utils.UniversalResult;
import com.nantian.model.security.User;
import com.nantian.security.JwtAuthenticationRequest;
import com.nantian.security.JwtTokenUtil;
import com.nantian.security.JwtUser;
import com.nantian.security.repository.UserRepository;
import com.nantian.security.service.JwtAuthenticationResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.mobile.device.Device;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class AuthenticationRestController {

    @Value("${jwt.header}")
    private String tokenHeader;

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private RoleAbilityMapper roleAbilityMapper;


    @RequestMapping(value = "${jwt.route.authentication.path}", method = RequestMethod.POST)
    public UniversalResult createAuthenticationToken(@RequestBody JwtAuthenticationRequest authenticationRequest, Device device) throws AuthenticationException {
        final Authentication authentication;
        String key, val, msg;
        User userInfo;
        Map dataMap = new HashMap();
        // Perform the security
        if (authenticationRequest.getPhoneNum() != null) {
            key = authenticationRequest.getPhoneNum() + "{{phoneNum}}";
            val = authenticationRequest.getConfirmCode();
            userInfo = userRepository.findByPhoneNum(authenticationRequest.getPhoneNum());
        } else {
            key = authenticationRequest.getUsername() + "{{userName}}";
            val = authenticationRequest.getPassword();
            userInfo = userRepository.findByUsername(authenticationRequest.getUsername());
        }

        authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                        key,
                        val
                )
        );
        SecurityContextHolder.getContext().setAuthentication(authentication);

        final UserDetails userDetails = userDetailsService.loadUserByUsername(key);
        final String token = jwtTokenUtil.generateToken(userDetails, device, userInfo.getUserid());
        dataMap.put("token", token);
        userInfo.setAuthorities(null);
        dataMap.put("userInfo", userInfo);
        /**
         * 获取用户前端权限点列表
         */
        List<String> ability = roleAbilityMapper.attachAbility(userInfo.getRoletype());
        dataMap.put("ability",ability);
        return new UniversalResult<>(UniversalResult.SUCCESS, "gfd", dataMap);
    }

    @RequestMapping(value = "${jwt.route.authentication.refresh}", method = RequestMethod.GET)
    public ResponseEntity<?> refreshAndGetAuthenticationToken(HttpServletRequest request) {
        String authToken = request.getHeader(tokenHeader);
        final String token = authToken.substring(7);
        String username = jwtTokenUtil.getUsernameFromToken(token);
        JwtUser user = (JwtUser) userDetailsService.loadUserByUsername(username);

        if (jwtTokenUtil.canTokenBeRefreshed(token, user.getLastPasswordResetDate())) {
            String refreshedToken = jwtTokenUtil.refreshToken(token);
            return ResponseEntity.ok(new JwtAuthenticationResponse(refreshedToken));
        } else {
            return ResponseEntity.badRequest().body(null);
        }
    }

}
